package com.itbaizhan.openhis.controller.system;

import com.itbaizhan.openhis.constants.Constants;
import com.itbaizhan.openhis.domain.Menu;
import com.itbaizhan.openhis.domain.SimpleUser;
import com.itbaizhan.openhis.dto.MenuDto;
import com.itbaizhan.openhis.service.MenuService;
import com.itbaizhan.openhis.utils.ShiroSecurityUtils;
import com.itbaizhan.openhis.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 */
@RestController
@RequestMapping("/system/menu")
@Slf4j
public class MenuController {
	
	@Autowired
	private MenuService menuService;
	
	/**
	 * 查询所有菜单及权限
	 *
	 * @param menuDto
	 * @return
	 */
	@GetMapping("listAllMenus")
	public AjaxResult listAllMenus(MenuDto menuDto) {
		log.info("查询所有菜单");
		List<Menu> list = menuService.listAllMenus(menuDto);
		return AjaxResult.success(list);
	}
	
	/**
	 * 根据角色ID查询菜单ID
	 *
	 * @param roleId
	 * @return
	 */
	@GetMapping("getMenuIdsByRoleId/{roleId}")
	public AjaxResult getMenuIdsByRoleId(@PathVariable Long roleId) {
		log.info("根据角色ID查询菜单ID");
		List<Long> menuIds = menuService.getMenuIdsByRoleId(roleId);
		return AjaxResult.success(menuIds);
	}
	
	/**
	 * 查询下拉菜单树
	 *
	 * @return
	 */
	@GetMapping("selectMenuTree")
	public AjaxResult selectMenuTrees() {
		log.info("查询菜单树");
		MenuDto menuDto = new MenuDto();
		menuDto.setStatus(Constants.STATUS_TRUE);//状态为正常de菜单
		
		return AjaxResult.success(menuService.listAllMenus(menuDto));
	}
	
	/**
	 * 根据菜单ID查询菜单权限
	 *
	 * @param menuId
	 * @return
	 */
	@GetMapping("getMenuById/{menuId}")
	public AjaxResult getMenuById(@PathVariable Long menuId) {
		log.info("查询菜单权限");
		return AjaxResult.success(menuService.getOne(menuId));
	}
	
	/**
	 * 添加菜单权限
	 * @param menuDto
	 * @return
	 */
	@PostMapping("addMenu")
	public AjaxResult addMenu(@Validated MenuDto menuDto) {
		log.info("添加菜单权限");
		menuDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
		return AjaxResult.toAjax(menuService.addMenu(menuDto));
	}
	
	/**
	 * 修改菜单权限
	 * @param menuDto
	 * @return
	 */
	@PutMapping("updateMenu")
	public AjaxResult updateMenu(@Validated MenuDto menuDto) {
		log.info("修改菜单权限");
		menuDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
		return AjaxResult.toAjax(menuService.updateMenu(menuDto));
	}
	
	/**
	 * 删除菜单权限
	 * @param menuId
	 * @return
	 */
	@DeleteMapping("deleteMenuById/{menuId}")
	public AjaxResult deleteMenuById(@PathVariable Long menuId) {
		log.info("删除菜单权限");
		if (menuService.hasChildByMenuId(menuId)) {
			return AjaxResult.fail("存在子菜单，不能删除");
		}
		return AjaxResult.toAjax(menuService.deleteMenuById(menuId));
	}
}
